/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.user;

import java.util.Random;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理用户信息的工具
 * 
 * @author peak
 * 
 */
public class UserKit {

	static Pattern REFERER_PATTERN = Pattern
			.compile("@([^\\s^\\:^\\,^\\;^<^>^&^@^\\[^\\]]{1,25})");// @.+?[\\s:]

	/**
	 * 处理提到某人，生成引用链接，参照了开源中国分享的代码：http://www.oschina.net/code/snippet_12_9258
	 * 
	 * @param msg
	 *            传入的文本内容
	 * @param referers
	 *            传出被引用的会员id列表
	 * @return 返回带链接的html
	 */
	public static String generateRefererLinks(String msg, Set<String> referers) {
		StringBuilder html = new StringBuilder();
		int lastIdx = 0;
		Matcher matcher = REFERER_PATTERN.matcher(msg);
		while (matcher.find()) {
			String origionStr = matcher.group();
			String nickname = origionStr.substring(1, origionStr.length())
					.trim();
			html.append(msg.substring(lastIdx, matcher.start()));
			User user = User.dao.findByNickname(nickname);
			if (user != null) {
				html.append("<a href='/user/show/" + user.getStr("id") + "'>@"
						+ nickname + "</a>");
				referers.add(user.getStr("id"));
			} else {
				html.append(origionStr);
			}
			lastIdx = matcher.end();

		}
		html.append(msg.substring(lastIdx));
		return html.toString();
	}

	/**
	 * 根据给定的字符串创建昵称，程序会把给定字符串一些字符剔除
	 * 
	 * @param str
	 * @return
	 */
	public static String buildNickname(String str) {
		return str.replaceAll("[\\s\\:\\,\\;<>&@\\[\\]]", "");
	}

	/**
	 * 检查昵称是否合乎规范
	 * 
	 * @param nickname
	 * @return
	 */
	public static boolean checkNickname(String nickname) {
		if (nickname == null) {
			return false;
		}
		return nickname.matches("^[^\\s^\\:^\\,^\\;^<^>^&^@^\\[^\\]]{3,10}$");
	}

	/**
	 * 生成一个唯一的昵称
	 * 
	 * @param nickname
	 * @return
	 */
	public static String makeUniqueNikname(String nickname) {
		nickname = buildNickname(nickname);
		if (nickname.length() > 10) {
			nickname = nickname.substring(0, 9);
		}
		if (!"".equals(nickname) && User.dao.findByNickname(nickname) == null) {
			return nickname;
		}
		Random random = new Random();
		while (true) {
			nickname = Integer.toString(random.nextInt());
			if (User.dao.findByNickname(nickname) == null) {
				return nickname;
			}
		}
	}

}
